package test

import (
	"bufio"
	"context"
	"log"
	"net/http"
	"sync"
	"time"
)

func testSSE(client *http.Client, url string, wg *sync.WaitGroup, workerID int) {
	defer wg.Done()

	// 创建请求
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Printf("Worker %d: Error creating request: %v", workerID, err)
		return
	}

	// 设置SSE所需的Accept头
	req.Header.Set("Accept", "text/event-stream")

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		log.Printf("Worker %d: Error making request: %v", workerID, err)
		return
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		log.Printf("Worker %d: Unexpected status code: %d", workerID, resp.StatusCode)
		return
	}

	// 读取SSE流
	scanner := bufio.NewScanner(resp.Body)
	eventCount := 0
	startTime := time.Now()

	// 设置超时上下文
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 创建一个通道来接收扫描结果
	lines := make(chan string)
	go func() {
		defer close(lines)
		for scanner.Scan() {
			select {
			case lines <- scanner.Text():
			case <-ctx.Done():
				return
			}
		}
	}()

	// 处理SSE事件
	for {
		select {
		case line, ok := <-lines:
			if !ok {
				log.Printf("Worker %d: Connection closed by server", workerID)
				return
			}
			if line != "" {
				eventCount++
				log.Printf("Worker %d: Received event: %s", workerID, line)
			}
		case <-ctx.Done():
			log.Printf("Worker %d: Test completed. Received %d events in %v",
				workerID, eventCount, time.Since(startTime))
			return
		}
	}
}
